var pickerFile = require('../../../../../../../ucenter/lib/picker_datetime/js/picker_datetime.js');
const util = require('../../../../../../../utils/util.js');
const api = require('../../../../../../../config/api.js');
const user = require('../../../../../../../services/user.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 单个票种信息
    oneTicket: {},
    // 数据下标
    ticketindex: '',
    //文字描述
    descDialog: { "show": false, "type": 0 },
    // 是否隐藏优惠时间的选择
    isHidePickerDatetime: true,
    projectdateStart: '',// 项目开始时间
    projectdateEnd: '',// 项目结束时间
    restrictionSettingArray: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.datetimePicker = new pickerFile.pickerDatetime({
      page: this,
      animation: 'slide',
      duration: 500
    });

    var projectdateStart = options.projectdateStart;
    var projectdateEnd = options.projectdateEnd;
    var ticketindex = options.ticketindex;
    var _this = this;
    _this.setData({
      ticketindex: ticketindex,
      projectdateStart: projectdateStart,
      projectdateEnd: projectdateEnd,
    })

    if (ticketindex != null && ticketindex != '') {
      var oneTicket = options.oneTicket;
      _this.setData({
        oneTicket: JSON.parse(oneTicket)
      })
      console.log(JSON.parse(oneTicket))
    }else{
      var oneTicket = {};
      oneTicket.id = "";
      oneTicket.name = "";
      oneTicket.price = "";// 原价，不填或填0为免费
      oneTicket.designatedType = 0;// 费用周期类型：0不限  1单次  2自定义
      oneTicket.designatedDays = 0;// 费用周期：0不限  1单次  其余的指定多少天就是多少
      oneTicket.numberPlaces = "";// 名额数量，不填为不限
      oneTicket.restrictionSetting = 1;//限购设置，必填的
      oneTicket.isOpenPreferentialSettings = 0;// 是否开启优惠设置：0否  1是
      oneTicket.preferentialSettings = "";// 票种类型：0打折优惠 1团购优惠 2橙贝互换
      oneTicket.preferentialdateStart = "";//优惠开始时间
      oneTicket.preferentialdateEnd = "";//优惠结束时间
      oneTicket.preferentialPrice = "";// 优惠金额，没有就不填
      oneTicket.orangeShell = "";//橙贝兑换价格
      oneTicket.isCommission = 0;// 是否开启分销：0否  1是
      oneTicket.commission = "";// 分销价格
      _this.setData({
        oneTicket: oneTicket
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 文字描述：打开
   */
  descDialogShow: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var descDialog = { "show": true, "type": type };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 文字描述：关闭
   */
  descDialogClose: function (e) {
    var _this = this;
    var descDialog = { "show": false, "type": 0 };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 票种名称输入事件
   */
  nameInput: function (e) {
    var _this = this;
    var value = e.detail.value.trim();
    _this.setData({
      ["oneTicket.name"]: value
    })
  },

  /**
   * 票种原价输入事件
   */
  priceInput: function (e) {
    var _this = this;
    var value = parseInt(e.detail.value);
    if (value > 10000) {
      util.dialogAlert("原价金额不可大于万元");
      value = 9999;
    } else if (value <= 0) {
      value = 0;
    }
    _this.setData({
      ["oneTicket.price"]: value
    })
  },

  /**
   * 橙贝兑换输入事件
   */
  orangeShellInput: function (e) {
    var _this = this;
    var value = parseInt(e.detail.value);
    _this.setData({
      ["oneTicket.orangeShell"]: value
    })
  },

  /**
   * 费用周期，类型选中事件
   */
  designatedType: function(e){
    var _this = this;
    var type = e.currentTarget.dataset.type;
    _this.setData({
      ["oneTicket.designatedType"]: type,
    })
    if (type == 0) {
      _this.setData({
        ["oneTicket.designatedDays"]: 0,
      })
    } else if (type == 1) {
      _this.setData({
        ["oneTicket.designatedDays"]: 1,
      })
    } else if(type == 2){
      var designatedDays = _this.data.designatedDays;
      if (!(designatedDays != 0 && designatedDays != 1)){
        _this.setData({
          ["oneTicket.designatedDays"]: '',
        })
      }
    }
  },

  /**
   * 费用周期指定天数输入事件
   */
  designatedDaysInput: function(e){
    var _this = this;
    var value = parseInt(e.detail.value);
    if (value <= 0) {
      value = 1;
    }
    _this.setData({
      ["oneTicket.designatedDays"]: value
    })
  },

  /**
   * 名额数量输入事件
   */
  numberPlacesInput: function (e) {
    var _this = this;
    var value = parseInt(e.detail.value);
    if (value <= 0) {
      value = 1;
    }
    _this.setData({
      ["oneTicket.numberPlaces"]: value
    })
  },

  /**
   * 限购设置输入事件
   */
  restrictionSettingInput: function (e) {
    var _this = this;
    var value = _this.data.restrictionSettingArray[e.detail.value];
    _this.setData({
      ["oneTicket.restrictionSetting"]: value
    })
  },

  /**
   * 是否开启优惠设置
   */
  isOpenPreferentialSettings: function(){
    var _this = this;
    var isOpenPreferentialSettings = _this.data.oneTicket.isOpenPreferentialSettings == 0 ? 1 : 0;
    _this.setData({
      ["oneTicket.isOpenPreferentialSettings"]: isOpenPreferentialSettings
    })
    var preferentialSettings = _this.data.oneTicket.preferentialSettings;
    if (preferentialSettings == '' || preferentialSettings == null){
      _this.setData({
        ["oneTicket.preferentialSettings"]: 0
      })
    }
  },

  /**
   * 优惠设置类型的改变
   */
  preferentialSettings: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    _this.setData({
      ["oneTicket.preferentialSettings"]: type
    })
  },

  /**
   * 优惠价格输入事件
   */
  preferentialPriceInput: function(e){
    var _this = this;
    var value = parseInt(e.detail.value);
    var preferentialSettings = parseInt(_this.data.oneTicket.preferentialSettings);
    var price = _this.data.oneTicket.price;
    if (value > 10000) {
      util.dialogAlert(_this.getPriceText(preferentialSettings) + "价格不可大于万元");
      value = 9999;
    } else{
      if (preferentialSettings == 0 || preferentialSettings == 1){
        if (value <= 0) {
          util.dialogAlert(_this.getPriceText(preferentialSettings) + "价格不能小于等于零元");
          value = 1;
        }
      } else if (preferentialSettings == 2){
        if (value <= 0) {
          util.dialogAlert(_this.getPriceText(preferentialSettings) + "价格不能小于零元");
          value = 0;
        }
      }
    }
    _this.setData({
      ["oneTicket.preferentialPrice"]: value
    })
  },

  /**
   * 价格校验
   */
  priceCheck: function(){
    var _this = this;
    var preferentialSettings = parseInt(_this.data.oneTicket.preferentialSettings);
    var price = parseInt(_this.data.oneTicket.price);
    var preferentialPrice = parseInt(_this.data.oneTicket.preferentialPrice);
    if (price >= 0 && preferentialPrice >= 0){
      if (price <= preferentialPrice) {
        util.dialogAlert(_this.getPriceText(preferentialSettings) + "价格不可大于等于原价");
        return false;
      }
    } else if (!(price >= 0) && preferentialPrice >= 0){
      util.dialogAlert("请输入原价");
      return false;
    }
    
    var commission = parseInt(_this.data.oneTicket.commission);
    if (price >= 0 && commission >= 0){
      if (preferentialPrice <= commission) {
        util.dialogAlert("分销价格不可大于等于" + _this.getPriceText(preferentialSettings) + "价格");
        return false;
      } else if (price <= commission) {
        util.dialogAlert("分销价格不可大于等于原价");
        return false;
      }
    } else if (!(price >= 0) && commission >= 0) {
      util.dialogAlert("请输入原价");
      return false;
    }
    return true;
  },

  /**
   * 优惠开始时间
   */
  preferentialdateStart: function(){
    var _this = this;
    var preferentialdateStart = _this.data.oneTicket.preferentialdateStart;
    if (preferentialdateStart == null || preferentialdateStart.length <= 0) {
      preferentialdateStart = util.haveSomeMinutesTime(60);
    }
    _this.datetimePicker.setPicker("oneTicket.preferentialdateStart", preferentialdateStart);
    _this.setData({
      isHidePickerDatetime: false
    })
  },

  /**
   * 优惠结束时间
   */
  preferentialdateEnd: function () {
    var _this = this;
    var preferentialdateEnd = _this.data.oneTicket.preferentialdateEnd;
    if (preferentialdateEnd == null || preferentialdateEnd.length <= 0) {
      preferentialdateEnd = util.haveSomeMinutesTime(120);
    }
    _this.datetimePicker.setPicker('oneTicket.preferentialdateEnd', preferentialdateEnd);
    _this.setData({
      isHidePickerDatetime: false
    })
  },

  /**
   * 开启圈子分销
   */
  commissionChange: function(){
    var _this = this;
    var isCommission = _this.data.oneTicket.isCommission == 0 ? 1 : 0;
    _this.setData({
      ["oneTicket.isCommission"]: isCommission
    })
    if (isCommission == 0){
      _this.setData({
        ["oneTicket.commission"]: ""
      })
    }
  },

  /**
   * 分销佣金输入事件
   */
  commissionInput: function(e){
    var _this = this;
    var value = parseInt(e.detail.value);
    if (value > 10000) {
      util.dialogAlert("分销佣金不可大于万元");
      value = 9999;
    } else if (value <= 0) {
      util.dialogAlert("分销佣金不能小于等于零元");
      value = 1;
    }
    _this.setData({
      ["oneTicket.commission"]: value
    })    
  },

  /**
   * 提交
   */
  submit: function(){
    var _this = this;
    var oneTicket = _this.data.oneTicket;
    if (!_this.verifyTicket()){
      return false;
    }
    if (oneTicket.id != null && String(oneTicket.id).length > 0) {
      var param = {};
      param.amountDetailsId = oneTicket.id;
      util.post(api.Interest_getTicketBuyCountUrl, param).then(function (res2) {
        if (res2.code == 200) {
          var count = res2.result.obj;
          if (count <= 0) {
            _this.submit2(oneTicket);
          } else {
            util.showToast("已有用户购买了票种，不能关闭付费设置~", "none");
          }
        }
      })
    }else{
      _this.submit2(oneTicket);
    }
  },

  submit2: function (oneTicket){
    var _this = this;
    var data = {};
    data.name = oneTicket.name == null ? "" : oneTicket.name;// 名称
    data.price = oneTicket.price == null ? "" : oneTicket.price;// 原价
    data.designatedType = oneTicket.designatedType == null ? 0 : oneTicket.designatedType;// 费用周期
    data.designatedDays = oneTicket.designatedDays == null ? 0 : oneTicket.designatedDays;// 周期天数
    data.numberPlaces = oneTicket.numberPlaces == null ? "" : oneTicket.numberPlaces;// 名额数量
    data.restrictionSetting = oneTicket.restrictionSetting == null ? 1 : oneTicket.restrictionSetting;// 限购设置
    data.isOpenPreferentialSettings = oneTicket.isOpenPreferentialSettings == null ? 0 : oneTicket.isOpenPreferentialSettings;// 是否开启优惠设置
    if (data.isOpenPreferentialSettings == 0) {
      data.preferentialPrice = "";
      data.preferentialdateStart = "";
      data.preferentialdateEnd = "";
      data.orangeShell = "";
      data.preferentialSettings = "";
    } else {
      data.preferentialSettings = oneTicket.preferentialSettings == null ? "" : oneTicket.preferentialSettings;// 优惠设置类型
      data.orangeShell = oneTicket.orangeShell == null ? "" : oneTicket.orangeShell;// 橙贝价格
      data.preferentialPrice = oneTicket.preferentialPrice == null ? "" : oneTicket.preferentialPrice;// 优惠价格
      data.preferentialdateEnd = oneTicket.preferentialdateEnd == null ? "" : oneTicket.preferentialdateEnd;// 优惠结束时间
      data.preferentialdateStart = oneTicket.preferentialdateStart == null ? "" : oneTicket.preferentialdateStart;// 优惠开始时间
    }
    data.id = oneTicket.id;
    data.isCommission = oneTicket.isCommission == null ? 0 : oneTicket.isCommission;//是否开启分销
    data.commission = oneTicket.commission == null ? "" : oneTicket.commission;// 分销金额
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];  //上一个页面
    var ticketindex = _this.data.ticketindex;
    var ticket = prevPage.data.ticket;
    if (ticketindex != null && ticketindex != "") {
      ticket[ticketindex] = data;
    } else {
      ticket.push(data);
    }
    prevPage.setData({
      ticket: ticket
    })
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 校验
   */
  verifyTicket: function () {
    var _this = this;
    var oneTicket = _this.data.oneTicket;
    var name = oneTicket.name;
    var designatedDays = parseInt(oneTicket.designatedDays);
    var restrictionSetting = oneTicket.restrictionSetting;
    var isOpenPreferentialSettings = parseInt(oneTicket.isOpenPreferentialSettings);
    var preferentialSettings = oneTicket.preferentialSettings;
    var preferentialPrice = parseInt(oneTicket.preferentialPrice);
    var orangeShell = parseInt(oneTicket.orangeShell);
    var preferentialdateStart = oneTicket.preferentialdateStart;
    var returnProjectdateidentification = oneTicket.returnProjectdateidentification;
    var preferentialdateEnd = oneTicket.preferentialdateEnd;
    var projectdateStart = _this.data.projectdateStart;
    var projectdateEnd = _this.data.projectdateEnd;
    var price = oneTicket.price;
    var isCommission = oneTicket.isCommission;
    var commission = oneTicket.commission;
    if (name.length <= 0) {
      util.dialogAlert("票种名称不能为空");
      return false;
    }
    if (!(designatedDays >= 0)) {
      util.dialogAlert("费用周期不能为空");
      return false;
    }
    if (restrictionSetting == null || restrictionSetting == "" || restrictionSetting <= 0) {
      util.dialogAlert("请输入限购设置");
      return false;
    }
    if(!_this.priceCheck()){
      return false;
    }
    if (isOpenPreferentialSettings == 1){
      if (!(price >= 0)){
        util.dialogAlert("请输入原价");
        return false;
      }
      if (!(preferentialPrice >= 0)) {
        util.dialogAlert("请输入" + _this.getPriceText(preferentialSettings) + "价格");
        return false;
      }
      if (preferentialSettings == 2 && !(orangeShell > 0)) {
        util.dialogAlert("请输入兑换橙贝数量");
        return false;
      }
      if (preferentialdateStart == null || preferentialdateStart == "") {
        util.dialogAlert("请输入" + _this.getPriceText(preferentialSettings) + "开始时间");
        return false;
      }
      if (preferentialdateEnd == null || preferentialdateEnd == "") {
        util.dialogAlert("请输入" + _this.getPriceText(preferentialSettings) + "结束时间");
        return false;
      }
      var dateStartTime = new Date(preferentialdateStart.replace(/\./g, '/')).getTime();
      var dateEndTime = new Date(preferentialdateEnd.replace(/\./g, '/')).getTime();
      var dateThisTime = new Date().getTime();
      /*
      因为会出现那种，修改的时候，时间有变化
      if (dateStartTime < dateThisTime) {
        util.dialogAlert(_this.getPriceText(preferentialSettings) + "开始时间不能小于当前时间");
        return false;
      }*/
      if (dateEndTime <= dateStartTime) {
        util.dialogAlert(_this.getPriceText(preferentialSettings) + "结束时间不能小于" + _this.getPriceText(preferentialSettings) +"开始时间");
        return false;
      }
      if (returnProjectdateidentification == 1 && projectdateStart != null && projectdateStart != '' && projectdateStart.length > 0) {
        var star = new Date(projectdateStart.replace(/-/g, '/')).getTime();
        if (dateStartTime < star) {
          util.dialogAlert(_this.getPriceText(preferentialSettings) + "开始时间不能小于项目开始时间");
          return false;
        }
      }
      if (returnProjectdateidentification == 1 && projectdateEnd != null && projectdateEnd != '' && projectdateEnd.length > 0) {
        var end = new Date(projectdateEnd.replace(/-/g, '/')).getTime();
        if (dateEndTime > end) {
          util.dialogAlert(_this.getPriceText(preferentialSettings) + "开始时间不能大于项目结束时间");
          return false;
        }
      }
    }
    if (isCommission == 1){
      if (!(commission > 0)) {
        util.dialogAlert("请输入分销佣金");
        return false
      }
    }
    return true;
  },

  /**
   * 获取价格的文字
   */
  getPriceText: function (preferentialSettings) {
    if (preferentialSettings == 0) {
      return "优惠";
    } else if (preferentialSettings == 1) {
      return "团购";
    } else {
      return "兑换";
    }
  },
})